package com.wtx.fitness.controller;

import com.wtx.fitness.common.Result;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.entity.Student;
import com.wtx.fitness.entity.Admin;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.exception.NotFoundException;
import com.wtx.fitness.exception.UnauthorizedException;
import com.wtx.fitness.mapper.AdminMapper;
import com.wtx.fitness.mapper.StudentMapper;
import com.wtx.fitness.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private AdminMapper adminMapper;

  /**
   * 获取当前用户信息
   */
  @GetMapping("/info")
  public Result<Map<String, Object>> getUserInfo() {
    // 从token中获取用户信息
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    Map<String, Object> userInfo = new HashMap<>();

    if ("student".equals(userType)) {
      Student student = studentMapper.findByStuId(userId);
      if (student == null) {
        throw new NotFoundException("用户不存在");
      }

      userInfo.put("id", student.getStuId());
      userInfo.put("username", student.getStuId());
      userInfo.put("name", student.getName());
      userInfo.put("gender", student.getGender());
      userInfo.put("type", "student");
      userInfo.put("avatarUrl", student.getAvatarUrl());
    } else if ("admin".equals(userType)) {
      Admin admin = adminMapper.findById(Integer.valueOf(userId));
      if (admin == null) {
        throw new NotFoundException("用户不存在");
      }

      userInfo.put("id", admin.getId());
      userInfo.put("username", admin.getUsername());
      userInfo.put("name", admin.getName());
      userInfo.put("type", "admin");
      userInfo.put("avatarUrl", admin.getAvatarUrl());
    } else {
      throw new BusinessException(ResultCode.PARAM_ERROR, "无效的用户类型");
    }

    return Result.success(userInfo);
  }

  /**
   * 修改密码
   */
  @PostMapping("/change-password")
  public Result<Void> changePassword(@RequestBody Map<String, String> params) {
    String oldPassword = params.get("oldPassword");
    String newPassword = params.get("newPassword");

    // 验证参数
    if (oldPassword == null || oldPassword.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "旧密码不能为空");
    }

    if (newPassword == null || newPassword.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "新密码不能为空");
    }

    // 从token中获取用户信息
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    int result = 0;

    if ("student".equals(userType)) {
      // 学生修改密码
      Student student = studentMapper.login(userId, oldPassword);
      if (student == null) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "旧密码错误");
      }

      result = studentMapper.updatePassword(userId, newPassword);
    } else if ("admin".equals(userType)) {
      // 管理员修改密码
      Admin admin = adminMapper.login(null, oldPassword);
      if (admin == null || !admin.getId().toString().equals(userId)) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "旧密码错误");
      }

      result = adminMapper.updatePassword(Integer.valueOf(userId), newPassword);
    } else {
      throw new BusinessException(ResultCode.PARAM_ERROR, "无效的用户类型");
    }

    if (result <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "修改密码失败");
    }

    return Result.success();
  }
}